import { CreepHelper } from "../../utils/creepHelper";

class UpgradeTask implements ICreepTask {
  public run(creep: Creep): void {
    // 控制器升级者 拿取资源然后升级房间内的控制器，取资源顺序 1.Storage 2.Container 3.地上捡，请注意虫子必须拿满了资源再对房间控制器进行升级
    if(creep.memory.working){
      // 对控制器进行签名
      if(creep.signController(creep.room.controller!, "It is always a pleasure to greet a friend from afar") == ERR_NOT_IN_RANGE) {
        creep.moveTo(creep.room.controller!);
      }
      // 如果虫子携带了能量资源，则执行升级控制器的逻辑
      let result = creep.upgradeController(creep.room.controller!);
      if(result == ERR_NOT_IN_RANGE){
        creep.go(creep.room.controller!.pos);
      }
      if(result == ERR_NOT_ENOUGH_RESOURCES){
        // 优先去link拿
        let controllerLinks = creep.room.controller?.pos.findInRange(FIND_STRUCTURES,1)
          .filter((structure)=> structure.structureType === STRUCTURE_LINK) as StructureLink[];
        if(controllerLinks && controllerLinks.length > 0){
          const link = controllerLinks[0];
          if(link && link.store.getUsedCapacity(RESOURCE_ENERGY) > 0){
            if(creep.withdraw(link, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE){
              creep.go(link);
            }
          }
          else {
            creep.memory.working = false;
          }
        }
        else {
          creep.memory.working = false;
        }
      }
    }else {
      //如果拾取未满最大容量则继续拾取
      CreepHelper.creepPickup(creep);
    }
  }
}

export { UpgradeTask };